package com.listeningframework.boot.autoconfigure.security.authentication;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Component;

/**
 * Custom Spring Security Authentication Manager
 * @author listening
 * @version $Id: ListeningAuthenticationManager.java, v 0.1 2015年8月23日   下午10:45:06 listening Exp $
 */
@Component
@ConditionalOnClass({ AuthenticationManager.class, AuthenticationManagerBuilder.class })
public class ListeningAuthenticationManager {
    /**
     * AuthenticationManager
     */
    @Autowired
    private AuthenticationManager        authenticationManager;
    /**
     * AuthenticationManagerBuilder
     */
    @Autowired
    private AuthenticationManagerBuilder authenticationManagerBuilder;

    /**
     * Authentication And Signin
     * 
     * @param username 用户名
     * @param password 密码
     */
    public void authentication(String username, String password) {
        Authentication authentication = new UsernamePasswordAuthenticationToken(username, password);
        Authentication result = authenticationManager.authenticate(authentication);
        SecurityContextHolder.getContext().setAuthentication(result);
    }

    /**
     * Get Default User Details Manager
     * 
     * @return UserDetailsManager
     */
    public UserDetailsManager getUserDetailsManager() {
        return (UserDetailsManager) authenticationManagerBuilder.getDefaultUserDetailsService();
    }

}
